<template>
  <div class="chat-container">
    <div class="chat-header">
      <h3>AI对话助手</h3>
    </div>
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="message in messages" :key="message.id" :class="['message', message.type]">
        <!-- 处理带思考内容的AI消息 -->
        <div v-if="message.type === 'ai' && message.thinking" class="thinking-container">
          <div class="thinking-header">
            已深度思考
          </div>
          <div class="thinking-content">
            <div class="thinking-item" v-for="(line, index) in message.thinking.split('\n')" :key="index">
              <span v-if="index === 0" class="thinking-icon">💡</span>
              <span class="thinking-text">{{ line.trim() }}</span>
            </div>
          </div>
        </div>
        <div class="message-content">{{ message.content }}</div>
        <div class="message-time">{{ message.time }}</div>
      </div>
    </div>
    <div class="chat-input-area">
      <textarea
        v-model="inputMessage"
        placeholder="请输入您的问题..."
        class="chat-input"
        @keydown.enter.ctrl="sendMessage"
      ></textarea>
      <div class="chat-actions">
        <el-button type="primary" @click="sendMessage" :loading="isLoading">
          <i class="el-icon-paper-plane"></i>
          发送
        </el-button>
        <el-button @click="resetInput" type="default">
          <i class="el-icon-refresh-left"></i>
          重置
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: 'AIChat',
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false
    };
  },
  mounted() {
    // 页面加载时显示欢迎消息
    this.addSystemMessage('欢迎使用AI对话助手，请问有什么可以帮助您的？');
  },
  methods: {
    // 添加系统消息
    addSystemMessage(content) {
      this.messages.push({
        id: 'system-' + Date.now(),
        type: 'system',
        content: content,
        time: this.formatTime(new Date())
      });
      this.scrollToBottom();
    },
    
    // 发送消息给AI
    async sendMessage() {
      const message = this.inputMessage.trim();
      if (!message || this.isLoading) {
        return;
      }

      // 添加用户消息到聊天记录
      this.messages.push({
        id: 'user-' + Date.now(),
        type: 'user',
        content: message,
        time: this.formatTime(new Date())
      });
      
      this.isLoading = true;
      this.inputMessage = '';
      this.scrollToBottom();

      try {
        // 调用API发送请求
        const response = await request({
          url: '/workspace/chat',
          method: 'post',
          data: {
            message: message,
            mode: 'chat',
            workspace: 'llm'
          }
        });

        // 解析响应，提取textResponse内容
        if (response.data && response.data.textResponse) {
          let content = response.data.textResponse;
          let thinkingContent = null;
          
          // 处理think标签内容
          if (content.includes('<think>') && content.includes('</think>')) {
            // 提取think标签内容
            const thinkStart = content.indexOf('<think>') + 7;
            const thinkEnd = content.indexOf('</think>');
            
            if (thinkEnd > thinkStart) {
              // 保存思考内容
              thinkingContent = content.substring(thinkStart, thinkEnd).trim();
              // 提取标签后的内容作为最终回答
              const afterThink = content.substring(thinkEnd + 8).trim();
              content = afterThink;
            }
          }
          
          // 添加AI回复到聊天记录
          const aiMessage = {
            id: 'ai-' + Date.now(),
            type: 'ai',
            content: content,
            time: this.formatTime(new Date())
          };
          
          // 如果有思考内容，添加到消息对象中
          if (thinkingContent) {
            aiMessage.thinking = thinkingContent;
          }
          
          this.messages.push(aiMessage);
        } else {
          this.addSystemMessage('抱歉，未能获取到AI的有效回复');
        }
      } catch (error) {
        console.error('发送消息失败:', error);
        this.addSystemMessage('发送消息失败，请稍后重试');
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    
    // 重置输入框
    resetInput() {
      this.inputMessage = '';
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    
    // 格式化时间
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
  box-sizing: border-box;
}

.chat-header {
  margin-bottom: 20px;
  text-align: center;
}

.chat-header h3 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.chat-messages {
  flex: 1;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  overflow-y: auto;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message {
  margin-bottom: 16px;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 70%;
  word-wrap: break-word;
}

.message.user {
  background-color: #e6f7ff;
  margin-left: auto;
  border-top-right-radius: 2px;
  /* 移除最大宽度限制，让文本框根据内容自适应 */
  max-width: none;
  min-width: 100px;
  width: fit-content;
  max-width: 90%; /* 添加最大宽度以防止内容过长 */
}

.message.ai {
  background-color: #f0f9ff;
  margin-right: auto;
  border-top-left-radius: 2px;
  position: relative;
}

/* 思考内容容器样式 */
.thinking-container {
  background-color: #e6f3ff;
  border: 1px solid #bae7ff;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}

/* 思考内容头部样式 */
.thinking-header {
  background-color: #bae7ff;
  padding: 8px 12px;
  font-size: 12px;
  color: #1890ff;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.thinking-header i {
  margin-right: 6px;
  font-size: 10px;
}

/* 思考内容区域样式 */
.thinking-content {
  padding: 12px;
  font-size: 13px;
  line-height: 1.6;
  color: #333;
  background-color: #f0f9ff;
}

/* 思考内容行样式 */
.thinking-item {
  margin-bottom: 8px;
  display: flex;
  align-items: flex-start;
}

.thinking-item:last-child {
  margin-bottom: 0;
}

/* 思考内容图标 */
.thinking-icon {
  margin-right: 8px;
  margin-top: 2px;
  font-size: 14px;
}

/* 思考内容文本 */
.thinking-text {
  flex: 1;
  word-wrap: break-word;
}

.message.system {
  background-color: #f5f5f5;
  margin: 0 auto 16px auto;
  text-align: center;
  font-style: italic;
  max-width: 100%;
}

.message-content {
  font-size: 14px;
  line-height: 1.5;
  color: #303133;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.chat-input-area {
  display: flex;
  flex-direction: column;
}

.chat-input {
  width: 100%;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  resize: none;
  margin-bottom: 12px;
  box-sizing: border-box;
}

.chat-input:focus {
  outline: none;
  border-color: #409eff;
}

.chat-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.chat-actions .el-button {
  padding: 10px 20px;
  font-size: 14px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    padding: 10px;
  }
  
  .message {
    max-width: 85%;
  }
}
</style>